package com.auto.survey.activity.monitoring.dao

import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Transaction
import androidx.room.Update
import com.auto.survey.activity.monitoring.entity.MonitoringStation
import com.auto.survey.activity.monitoring.entity.ctrlmeasure.StationWithClosedLoop
import com.auto.survey.activity.monitoring.entity.relations.MonitoringWithStationsAndPoints
import kotlinx.coroutines.flow.Flow

/**
 * 测站数据访问对象接口
 * 定义与测站相关的数据库操作
 */
@Dao
interface MonitoringStationDao {

    /**
     * 根据监测对象ID获取测站列表
     * @param objectId 监测对象ID
     * @return 测站列表Flow流
     */
    @Query("SELECT * FROM MonitoringStation WHERE monitoringObjectId = :objectId ORDER BY id DESC")
    fun getStationsByObjectId(objectId: Int): Flow<List<MonitoringStation>>

    /**
     * 根据测站ID获取测站信息
     * @param id 测站ID
     * @return 测站实体或null
     */
    @Query("SELECT * FROM MonitoringStation WHERE id = :id")
    suspend fun getMonitoringStationById(id: Int): MonitoringStation?

    /**
     * 插入新测站
     * @param station 测站实体
     * @return 插入的测站ID
     */
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertMonitoringStation(station: MonitoringStation): Long

    /**
     * 更新测站信息
     * @param station 测站实体
     */
    @Update
    suspend fun updateMonitoringStation(station: MonitoringStation)

    /**
     * 删除测站
     * @param station 测站实体
     */
    @Delete
    suspend fun deleteMonitoringStation(station: MonitoringStation)

    /**
     * 根据测站ID删除测站
     * @param id 测站ID
     */
    @Query("DELETE FROM MonitoringStation WHERE id = :id")
    suspend fun deleteMonitoringStationById(id: Int)

    /**
     * 获取监测对象下的测站数量
     * @param objectId 监测对象ID
     * @return 测站数量
     */
    @Query("SELECT COUNT(*) FROM MonitoringStation WHERE monitoringObjectId = :objectId")
    suspend fun getMonitoringStationCountByObjectId(objectId: Int): Int

    /**
     * 查询单个站点及其关联的所有闭合观测序列
     */
    @Transaction
    @Query("SELECT * FROM MonitoringStation WHERE id = :stationId")
    suspend fun getStationWithClosedLoops(stationId: Int): StationWithClosedLoop?

}